package com.youthfilmic.yuejian.controller;

import com.youthfilmic.yuejian.conn.WeixinConn;
import com.youthfilmic.yuejian.dao.LoginRecordDao;
import com.youthfilmic.yuejian.dao.SubjectDao;
import com.youthfilmic.yuejian.dao.UserDao;
import com.youthfilmic.yuejian.domain.*;
import com.youthfilmic.yuejian.service.UserService;
import com.youthfilmic.yuejian.util.MobileCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * Created by youweixi on 15/10/7.
 */
@Controller
public class PageController {
    @Resource
    private SubjectDao subjectDao;
    @Resource
    private UserDao userDao;
    @Autowired
    private UserService userService;
    @Resource
    private LoginRecordDao recordDao;

    @RequestMapping("/main/index")
    public String showIndex(
            HttpSession session,
            @RequestParam(value="cityId" , required = false) Integer cityId,
            Model model
    ){
        Page<Subject> page = null;
        if(cityId == null){
            page = subjectDao.findByStatus(Subject.SATUS_SUCCEED, new PageRequest(0, 20,new Sort(Sort.Direction.DESC , "postAt")));

        }else{
            page = subjectDao.findByCityAndStatus(cityId, Subject.SATUS_SUCCEED, new PageRequest(0, 20,new Sort(Sort.Direction.DESC , "postAt")));
        }
        //if (cityId == null) cityId = 0;
        model.addAttribute("cityId" , cityId);
        model.addAttribute("subjects" , page.getContent());
        model.addAttribute("cities" , DomainInfo.getCityMap());
        return "main/index";
    }

    @RequestMapping("/main/logout")
    public String showIndex(
            HttpSession session
    ){
        session.removeAttribute("userIdForBind");
        session.removeAttribute("userId");
        return "redirect:/main/index";
    }

    @RequestMapping("/main/discovery")
    public String showDiscovery(Model model){
        Page<Subject> page = subjectDao.findByStatus(Subject.SATUS_SUCCEED , new PageRequest(0 , 30,new Sort(Sort.Direction.DESC , "postAt")));
        model.addAttribute("subjects", page.getContent());
        return "main/discovery";
    }

    /**
     * 显示错误页面
     * 404 500 503
     * */
    @RequestMapping("/error/{type}")
    public String showError(
            @PathVariable("type") String type
    ){
        return "main/error/" + type;
    }

    @RequestMapping("/message")
    public String showMessage(
            @RequestParam(value="action" , required = false) String action
    ){
        return "main/message";
    }


    @RequestMapping("/bind")
    public String showBind(
            HttpSession session,
            Model model
    ){
        Long userId = (Long) session.getAttribute("userId");
        if (userId != null){
            User user = userDao.findOne(userId);
            model.addAttribute("user",user);
        }
        return "bind";
    }

    @RequestMapping("/bind.do")
    public String doBind(
            @RequestParam(value="phone" , required = false) String phone,
            @RequestParam(value="code" , required = false) String code,
            HttpSession session
    ){
        Long userId = (Long) session.getAttribute("userIdForBind");
        if (!MobileCodeUtil.verifyPhoneAndCode(phone, code)){
            return "redirect:/bind?error=code_wrong&phone=" + phone;
        }else{
            if (userId != null){
                User user = userDao.findOne(userId);
                user.setPhone(phone);
                userDao.save(user);

                session.setAttribute("userId" , user.getId());
                //记录登录行为
                LoginRecord record = new LoginRecord(user);
                recordDao.save(record);
                return "redirect:/main/index";
            }else{
                WeixinOAuthInfo info = (WeixinOAuthInfo) session.getAttribute("weixinOAuthInfo");
                if (info == null){
                    return "redirect:/main/index";
                }
                User user = null;
                try {
                    user = userService.createNewUser(info.getOpenId() , WeixinConn.OPENID_FROM_CURRENT , info.getUnionId() , info.getNickName() ,info.getPicUrl(), info.getSex() , phone);
                } catch (Exception e) {
                    e.printStackTrace();
                    return "redirect:/main/index";
                }
                //执行登录
                session.setAttribute("userId" , user.getId());
                //记录登录行为
                LoginRecord record = new LoginRecord(user);
                recordDao.save(record);
                return "redirect:" + info.getTargetUrl();
            }
        }
    }


}
